package com.zyj.test.month1.day1;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Yijia Zhang
 * @create 2024-04-18 22:00
 */
public class code2007 {
    public int[] findOriginalArray(int[] changed) {
        Map<Integer, Integer> map = new HashMap<> ();
        int len = changed.length;
        if (len % 2 != 0) {
            return emptyArray();
        }
        Arrays.sort(changed);
        for (int i : changed) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        int[] res = new int[len >> 1];
        int idx = 0;
        for (int i = 0; i < len; i++) {
            int num = changed[i];
            int curCount = map.get(num);
            if (curCount <= 0) {
                continue;
            }
            map.put(num, curCount - 1);
            if (map.getOrDefault(num << 1, 0) > 0) {
                res[idx++] = num;
                map.put(num << 1, map.get(num << 1) - 1);
            } else {
                return emptyArray();
            }
        }
        return idx == len >> 1 ? res : emptyArray();


    }
    public int[] findOriginalArray_sort_fail(int[] changed) {
        int len = changed.length;
        if (len % 2 != 0) {
            return emptyArray();
        }
        Arrays.sort(changed);
        int p2 = len >> 1;
        int p1 = 0;
        while (p2 < len) {
            if ((changed[p1] << 1) != changed[p2]) {
                return emptyArray();
            }
            p2++;
            p1++;
        }
        return Arrays.copyOf(changed, len >> 1);
    }

    private int[] emptyArray() {
        return new int[0];
    }

    public static void main(String[] args) {
        code2007 code2007 = new code2007();
        int[] originalArray = code2007.findOriginalArray(new int[]{3,3,3,3});
        System.out.println(Arrays.toString(originalArray));
    }
}
